<?php

namespace interface\v1;

/*
*食堂接口类
*/

class canteenAppClass extends index
{
    private const page = 'diningHall';
    public array $weekArray = array("日", "一", "二", "三", "四", "五", "六");

    /**
     * 报餐页面
     */
    public function mealReport()
    {
        //数据查询
        $month = $this->post('month');//切换月份
        $mealType = $this->post('mealType') ?: '早餐';

        if ($month) {
            $date = $month . '-01';
        } else {
            $date = $this->post('date') ?: $this->date;
        }
        $this->code = 1;
        $month = date('Y-m', strtotime($date));//月份
        $days = date('t', strtotime($date));  //此月份总天数
        $dayArr = [];
        $now_week = date('w', strtotime(date('Y-m-01', strtotime($date))));

        //获取当前人所在食堂
        $hall = query('dining_hall', "member like '%" . self::$stid . "%' and state = '启用' order by time desc");
        if (empty($hall['id'])) {
            $this->resp['warn'] = '未找到您可以就餐的食堂';
        } else {
            $isReport = 0;
            //判断的当前是否已报过餐了
            $meal_report = query('meal_report', "hallId = '$hall[id]' and mealType = '$mealType' and recordDate = '$date' and staffId = '" . self::$stid . "'");
            if (!empty($meal_report['id'])) {
                $isReport = 1;
            }
            //获取此食堂今天的菜单
            $menu_list = [];
            $mealTypeOption = explode('，', para('mealOption'));
            $all = find(array('table' => "dining_week_menu as a join dining_week_menu_detail as b on a.id = b.orderId", 'where' => "hallId = '$hall[id]' and b.mealType='$mealType' and b.localDate = '$date' and a.state = '启用' order by b.list asc"));
            foreach ($all['array'] as $array) {
                $meun = query('dining_menu', "id = '$array[menuId]'");
                $img = query('file', "targetId = '$array[menuId]' order by time asc");
                $meal_report_detail = query('meal_report_detail', "orderId = '$meal_report[id]' and menuId = '$array[menuId]'");

                $menu_list[] = [
                    'id' => $array['id'],
                    'menuId' => $array['menuId'],
                    'type' => $meun['type'],
                    'name' => $meun['name'],
                    'ico' => self::fillSrc($img['src']),
                    'isCanChoose' => $meun['isEnable'],
                    'num' => $meal_report_detail['num'] ?: 0,
                ];
            }
            for ($i = 0; $i < $now_week; $i++) {
                $dayArr[] = [
                    'index' => ' ',
                    'state' => ' ',
                    'date' => ' ',
                ];
            }
            for ($i = 1; $i <= $days; $i++) {
                $today = $month . '-' . sprintf("%02d", $i);
                $dayArr[] = [
                    'index' => $i,
                    'date' => $today,
                    'state' => '',
                ];
            }
            //取餐记录
            $takeRecord = query('meal_take_record', "reportId = '$meal_report[id]'");
            $data['result'] = [
                'date' => $date,
                'month' => $month,
                'formatDate' => date('m月d日', strtotime($date)) . ' 周' . $this->weekArray[date("w", strtotime($date))] . ' ' . ($date == $this->date ? '(今天)' : ''),
                'list' => $dayArr,
                'menu' => $menu_list,
                'mealOption' => $mealTypeOption,
                'nowMealType' => $mealType,//当前餐别
                'isReport' => $isReport,//是否已报过餐
                'person' => [
                    'name' => $this->control['name'],
                    'ico' => self::fillSrc($this->control['ico']),
                    'hallName' => $hall['name'],
                    'hallId' => $hall['id'],
                ],
                'record' => [
                    'id' => $meal_report['id'],
                    'date' => $meal_report['recordDate'],
                    'mealType' => $meal_report['mealType'],
                    'type' => $meal_report['type'],
                    'num' => $meal_report['num'],
                    'stName' => self::findStaff($meal_report['stid']),
                    'time' => $meal_report['time'],
                    'takeType' => $takeRecord['type'],
                    'takeStName' => self::findStaff($takeRecord['staffId']),
                    'takeTime' => $takeRecord['time'],
                    'state' => $takeRecord['id'] ? '已取餐' : '待取餐'
                ]
            ];
            $this->resp['data'] = $data;
        }
    }

    /**
     * 报餐提交
     */
    public function reportEdit()
    {
        $hallId = $this->post('hallId');
        $date = $this->post('date');
        $type = $this->post('type');
        $menu = $_POST['menu'] ? json_decode($_POST['menu'], true) : [];
        $mealType = $this->post('mealType');
        $hall = query('dining_hall', "id = '$hallId'");
        $flag = true;
        if (is_array($menu)) {
            foreach ($menu as $val) {
                if (!empty($val['num'])) {
                    $flag = false;
                    break;
                }
            }
        }

        $staffId = $type == '代报餐' ? $this->post('staffId') : self::$stid;

        $hall_detail = query('dining_hall_detail', "orderId = '$hall[id]' and mealType = '$mealType' order by list asc");
        if (empty($hall['id'])) {
            $this->resp['warn'] = '未找到此食堂';
        } elseif (!str_contains($hall['member'], self::$stid)) {
            $this->resp['warn'] = '您不在此食堂可报餐人员中';
        } elseif (empty($date)) {
            $this->resp['warn'] = '未找到日期';
        } elseif (empty($mealType) || !in_array($mealType, explode('，', para('mealOption')))) {
            $this->resp['warn'] = '未找到餐别';
        } elseif (empty($menu)) {
            $this->resp['warn'] = '请选择菜品';
        } elseif ($flag) {
            $this->resp['warn'] = '请选择菜品';
        } elseif (empty($hall_detail['id'])) {
            $this->resp['warn'] = '未找到此食堂报餐时间';
        } elseif (strtotime($date . ' ' . $hall_detail['endTime']) < time() && in_array($mealType,['午餐','晚餐','宵夜'])) {
            $this->resp['warn'] = '已过了' . $mealType . '的报餐时间，'.$mealType.'的报餐截止时间为：'.$hall_detail['endTime'];
        }elseif(strtotime(date('Y-m-d',strtotime("-1 day",strtotime($date))) . ' ' . $hall_detail['endTime']) < time() && $mealType == '早餐'){
            $this->resp['warn'] = '已过了' . $mealType . '的报餐时间，'.$mealType.'的报餐截止时间为：'.$hall_detail['endTime'];
        }elseif (self::total(array('table' => 'meal_report', 'where' => "hallId = '$hall[id]' and mealType = '$mealType' and recordDate = '$date' and staffId = '" . $staffId . "'")) > 0) {
            $this->resp['warn'] = '您已报餐，不能重复报餐';
        } elseif (empty($staffId)) {
            $this->resp['warn'] = '未找到员工ID';
        } elseif (empty($type)) {
            $this->resp['warn'] = '未找到报餐类型';
        } else {
            //判断当前时间是否可报餐
            $this->startTrans();
            $id = self::getId();
            $warn = static::insert(array(
                'table' => 'meal_report',
                'field' => [
                    'id' => $id,
                    'recordDate' => $date,
                    'hallId' => $hall['id'],
                    'mealType' => $mealType,
                    'type' => $type,
                    'departmentId' => self::findStaffDepartment($staffId),
                    'staffId' => $staffId,
                    'num' => 1,
                    'stid' => self::$stid,
                    'workFlow' => '待取餐',
                    'text' => $this->post('text')
                ]
            ));
            foreach ($menu as $val) {
                if ($val['num'] > 0) {
                    $bool = static::insert(array(
                        'table' => 'meal_report_detail',
                        'field' => [
                            'id' => self::getId(),
                            'orderId' => $id,
                            'menuId' => $val['menuId'],
                            'num' => $val['num'],
                        ]
                    ));
                    if ($bool != '新增成功') {
                        $warn = $bool;
                        break;
                    }
                }
            }
            if ($warn == '新增成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '报餐成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = $warn;
            }
        }
    }

    /**
     * 取消报餐
     */
    public function cancelReport()
    {
        $id = $this->post('id');
        $report = query('meal_report', "id = '$id' and stid = '" . self::$stid . "'");
        $hall_detail = query('dining_hall_detail', "orderId = '$report[hallId]' and mealType = '$report[mealType]' order by list asc");
        if (empty($report['id'])) {
            $this->resp['warn'] = '未找到您的报餐记录';
        } elseif (self::total(array('table' => 'meal_take_record', 'where' => "reportId = '$report[id]'")) > 0) {
            $this->resp['warn'] = '您已取餐，不能取消';
        } elseif(time() > strtotime($report['recordDate'].' '.$hall_detail['endTime'])){
            $this->resp['warn'] = '已经过了'.$report['mealType'].'报餐时间了';
        }else {
            $this->startTrans();
            $warn = delete(array('table' => 'meal_report', 'where' => "id = '$id'"));
            $bool = delete(array('table' => 'meal_report_detail', 'where' => "orderId = '$id'"));
            if ($bool != '删除成功') {
                $warn = $bool;
            }
            if ($warn == '删除成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '取消成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = '取消失败';
            }
        }
    }

    /**
     * 功能
     */
    public function func()
    {
        $userPower = self::getUserPower();
        $data['result']['menu'] = [
            [
                'name' => '报餐取餐',
                'array' => [
                    [
                        'name' => '报餐',
                        'ico' => oaIndexAppClass::icon('workSignAdd'),
                        'power' => true,
                        'url' => ''
                    ],
                    [
                        'name' => '代报餐',
                        'ico' => oaIndexAppClass::icon('holiday'),
                        'power' => true,
                        'url' => '../mealAsk/mealAsk'
                    ],
                    [
                        'name' => '申请客餐',
                        'ico' => oaIndexAppClass::icon('out'),
                        'power' => true,
                        'url' => '../clientMeal/clientMeal'
                    ],
                    [
                        'name' => '代取餐',
                        'ico' => oaIndexAppClass::icon('workAdd'),
                        'power' => true,
                        'url' => '../takeMeal/takeMeal'
                    ],
                    [
                        'name' => '食堂评价',
                        'ico' => oaIndexAppClass::icon('dayReport'),
                        'power' => true,
                        'url' => '../evaluat/evaluat'
                    ],
                ]
            ],
            [
                'name' => '数据统计',
                'array' => [
                    [
                        'name' => '报餐取餐',
                        'ico' => oaIndexAppClass::icon('feeApply'),
                        'power' => 'mealStatistics',
                        'url' => '../mealStatistics/mealStatistics'
                    ]
                ]
            ]
        ];
        foreach ($data['result']['menu'] as $index => $array) {
            foreach ($array['array'] as $num => $val) {
                if (!array_key_exists($val['power'], $userPower) && $val['power'] !== true) {
                    unset($data['result']['menu'][$index]['array'][$num]);
                }
            }
        }
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;

    }

    /*查询条件*/
    public function replaceReportSearch()
    {
        $where = '';
        //状态
        $data['mealOption'] = explode('，', para('mealOption'));
        $data['stateOption'] = ['待取餐', '已取餐'];
        $data['timeOption'] = $this->timeOption;
        $where = $this->post('type')=='all'?'1=1':"state = '启用'";
        $data['hallOption'] = find(array('table' => 'dining_hall', 'field' => "id,name", "where" => "{$where} order by time "))['array'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 代报餐
     */
    public function replaceReportMeal()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            'type' => '代报餐',
            'workFlow' => $this->post('workFlow'),
            'mealType' => $this->post('mealType'),
        );
        //初始化
        $and = '';
        if ($this->post('keyword')) {
            $and .= " and staffId in ( select stid from staff where name like '%" . $this->post('keyword') . "%')";
        }
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime, field: 'recordDate');
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => 'meal_report', "where" => $where, "order" => "recordDate desc,time desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $hall = query('dining_hall', "id = '$array[hallId]'");
            $take = query('meal_take_record', "reportId = '$array[id]'");
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'stName' => self::findStaff($array['staffId']),
                "hallName" => $hall['name'],
                "workFlow" => $array['workFlow'],
                "recordDate" => $array['recordDate'],//状态
                "mealType" => $array['mealType'],
                "num" => $array['num'],
                "type" => $array['type'],
                "askStName" => self::findStaff($array['stid']),
                'time' => $array['time'],
                'takeStName' => self::findStaff($take['staffId']) ?: ' ',
                'takeType' => $take['type'] ?: ' ',
                'takeTime' => $take['time'] ?: ' ',
                'menu' => $this->getMenuMx($array['id'])
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 获取菜品明细
     */
    public function getMenuMx($pid): string
    {
        $str = '';
        $menuMx = find(array('table' => "meal_report_detail as a join dining_menu as b on a.menuId = b.id", "where" => "orderId = '$pid' group by orderId,menuId", 'field' => "b.name as menuName,ifnull(sum(a.num),0) as totalNum"));
        foreach ($menuMx['array'] as $array) {
            $str .= $array['menuName'] . ':' . $array['totalNum'] . ';';
        }
        return $str;
    }

    /**
     * 根据员工ID获取食堂
     */
    public function getCanteen()
    {
        $staffId = $this->post('staffId');
        if (empty($staffId)) {
            $this->resp['warn'] = '未获取到员工ID';
        } else {
            $hall = query('dining_hall', "member like '%" . $staffId . "%' and state = '启用' order by time desc");
            if (empty($hall['id'])) {
                $this->resp['warn'] = '未找到可以就餐的食堂';
            } else {
                $this->code = 1;
                $this->resp['data'] = [
                    'canteen' => $hall['name'],
                    'hallId' => $hall['id']
                ];
            }
        }
    }

    /**
     * 获取菜单
     */
    public function getMenu()
    {
        $menu_list = [];
        $all = find(array('table' => "dining_week_menu as a join dining_week_menu_detail as b on a.id = b.orderId", 'where' => "hallId = '" . $this->post('hallId') . "' and b.mealType='" . $this->post('mealType') . "' and b.localDate = '" . $this->post('recordDate') . "' and a.state = '启用' order by b.list asc"));
        foreach ($all['array'] as $array) {
            $meun = query('dining_menu', "id = '$array[menuId]'");
            $img = query('file', "targetId = '$array[menuId]' order by time asc");
            $menu_list[] = [
                'id' => $array['id'],
                'menuId' => $array['menuId'],
                'type' => $meun['type'],
                'name' => $meun['name'],
                'ico' => self::fillSrc($img['src']),
                'isCanChoose' => $meun['isEnable'],
                'num' => 0,
            ];
        }
        $this->code = 1;
        $this->resp['data'] = [
            'menu' => $menu_list,
        ];
    }

    /**
     * 报餐提交
     */
    public function replaceReportEdit()
    {
        $hallId = $this->post('hallId');
        $date = $this->post('date');
        $type = $this->post('type');
        $menu = $_POST['menu'] ? json_decode($_POST['menu'], true) : [];
        $mealType = $this->post('mealType');
        $hall = query('dining_hall', "id = '$hallId'");
        $flag = true;
        if (is_array($menu)) {
            foreach ($menu as $val) {
                if (!empty($val['num'])) {
                    $flag = false;
                    break;
                }
            }
        }

        $hall_detail = query('dining_hall_detail', "orderId = '$hall[id]' and mealType = '$mealType' order by list asc");
        if (empty($hall['id'])) {
            $this->resp['warn'] = '未找到此食堂';
        } elseif (!str_contains($hall['member'], self::$stid)) {
            $this->resp['warn'] = '您不在此食堂可报餐人员中';
        } elseif (empty($date)) {
            $this->resp['warn'] = '未找到日期';
        } elseif (empty($mealType) || !in_array($mealType, explode('，', para('mealOption')))) {
            $this->resp['warn'] = '未找到餐别';
        } elseif (empty($menu)) {
            $this->resp['warn'] = '请选择菜品';
        } elseif ($flag) {
            $this->resp['warn'] = '请选择菜品';
        } elseif (empty($hall_detail['id'])) {
            $this->resp['warn'] = '未找到此食堂报餐时间';
        } elseif (strtotime($this->date . ' ' . $hall_detail['endTime']) < time()) {
            $this->resp['warn'] = '已过了' . $mealType . '的报餐时间';
        } elseif (self::total(array('table' => 'meal_report', 'where' => "hallId = '$hall[id]' and mealType = '$mealType' and recordDate = '$date' and staffId = '" . self::$stid . "'")) > 0) {
            $this->resp['warn'] = '您已报餐，不能重复报餐';
        } elseif (empty($type)) {
            $this->resp['warn'] = '未找到报餐类型';
        } else {
            //判断当前时间是否可报餐
            $this->startTrans();
            $id = self::getId();
            $warn = static::insert(array(
                'table' => 'meal_report',
                'field' => [
                    'id' => $id,
                    'recordDate' => $date,
                    'hallId' => $hall['id'],
                    'mealType' => $mealType,
                    'type' => $type,
                    'departmentId' => self::findStaffDepartment(self::$stid),
                    'staffId' => '',
                    'num' => 1,
                    'stid' => self::$stid,
                    'workFlow' => '待取餐',
                    'text' => $this->post('text')
                ]
            ));
            foreach ($menu as $val) {
                if ($val['num'] > 0) {
                    $bool = static::insert(array(
                        'table' => 'meal_report_detail',
                        'field' => [
                            'id' => self::getId(),
                            'orderId' => $id,
                            'menuId' => $val['menuId'],
                            'num' => $val['num'],
                        ]
                    ));
                    if ($bool != '新增成功') {
                        $warn = $bool;
                        break;
                    }
                }
            }
            if ($warn == '新增成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '报餐成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = $warn;
            }
        }
    }

    /**
     * 客餐列表
     */
    public function clientMeal()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            'type' => '申请客餐',
            'workFlow' => $this->post('workFlow'),
            'mealType' => $this->post('mealType'),
        );

        $like = array(
            'company' => $this->post('keyword'),
        );
        //初始化
        $and = '';
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime, field: 'recordDate');
        }
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array("table" => 'meal_report', "where" => $where, "order" => "recordDate desc,time desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $hall = query('dining_hall', "id = '$array[hallId]'");
            $take = query('meal_take_record', "reportId = '$array[id]'");
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'stName' => $array['company'],
                "hallName" => $hall['name'],
                "workFlow" => $array['workFlow'],
                "recordDate" => $array['recordDate'],//状态
                "mealType" => $array['mealType'],
                "num" => $array['num'],
                "type" => $array['type'],
                "askStName" => self::findStaff($array['stid']),
                'time' => $array['time'],
                'takeStName' => self::findStaff($take['staffId']) ?: ' ',
                'takeType' => $take['type'] ?: ' ',
                'takeTime' => $take['time'] ?: ' ',
                'menu' => $this->getMenuMx($array['id'])
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 申请客餐编辑
     */
    public function clientMealEdit()
    {
        $hallId = $this->post('hallId');
        $date = $this->post('date');
        $menu = $_POST['menu'] ? json_decode($_POST['menu'], true) : [];
        $mealType = $this->post('mealType');
        $hall = query('dining_hall', "id = '$hallId'");
        $flag = true;
        if (is_array($menu)) {
            foreach ($menu as $val) {
                if (!empty($val['num'])) {
                    $flag = false;
                    break;
                }
            }
        }
        $company = $this->post('company');
        $hall_detail = query('dining_hall_detail', "orderId = '$hall[id]' and mealType = '$mealType' order by list asc");
        if (empty($hall['id'])) {
            $this->resp['warn'] = '未找到此食堂';
        } elseif (empty($date)) {
            $this->resp['warn'] = '未找到日期';
        } elseif (empty($mealType) || !in_array($mealType, explode('，', para('mealOption')))) {
            $this->resp['warn'] = '未找到餐别';
        } elseif (empty($menu)) {
            $this->resp['warn'] = '请选择菜品';
        } elseif ($flag) {
            $this->resp['warn'] = '请选择菜品';
        } elseif (empty($hall_detail['id'])) {
            $this->resp['warn'] = '未找到此食堂报餐时间';
        } /*elseif (strtotime($this->date . ' ' . $hall_detail['endTime']) < time()) {
            $this->resp['warn'] = '已过了' . $mealType . '的报餐时间';
        } */ elseif (self::total(array('table' => 'meal_report', 'where' => "hallId = '$hall[id]' and mealType = '$mealType' and recordDate = '$date' and company = '" . $company . "'")) > 0) {
            $this->resp['warn'] = '已为此客户报餐，不能重复报餐';
        } elseif (empty($this->post('num'))) {
            $this->resp['warn'] = '至少选择一份';
        } elseif (empty($company)) {
            $this->resp['warn'] = '请填写来访单位';
        } else {
            //判断当前时间是否可报餐
            $this->startTrans();
            $id = self::getId();
            $warn = static::insert(array(
                'table' => 'meal_report',
                'field' => [
                    'id' => $id,
                    'recordDate' => $date,
                    'hallId' => $hall['id'],
                    'mealType' => $mealType,
                    'type' => '申请客餐',
                    'company' => $company,
                    'departmentId' => self::findStaffDepartment(self::$stid),
                    'staffId' => self::$stid,
                    'num' => $this->post('num'),
                    'stid' => self::$stid,
                    'workFlow' => '待取餐',
                    'text' => $this->post('text')
                ]
            ));
            foreach ($menu as $val) {
                if ($val['num'] > 0) {
                    $bool = static::insert(array(
                        'table' => 'meal_report_detail',
                        'field' => [
                            'id' => self::getId(),
                            'orderId' => $id,
                            'menuId' => $val['menuId'],
                            'num' => $val['num'],
                        ]
                    ));
                    if ($bool != '新增成功') {
                        $warn = $bool;
                        break;
                    }
                }
            }
            if ($warn == '新增成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '报餐成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = $warn;
            }
        }
    }

    /**
     * 代取餐
     */
    public function takeMeal()
    {
        //全等查询数组
        $equal = array(
            "stid" => self::$stid,//员工
            'mealType' => $this->post('mealType'),
        );

        $like = array(
            'company' => $this->post('keyword'),
        );
        //初始化
        $and = '';
        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and .= $this->miniTimeComparison($commitTime, field: 'recordDate');
        }
        //获取查询结果
        $where = search(array("=" => $equal, 'like' => $like)) . $and;
        $page = $this->page(array("table" => 'meal_take_record_parent', "where" => $where, "order" => "recordDate desc,time desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $hall = query('dining_hall', "id = '$array[hallId]'");
            $take = query('meal_take_record', "reportId = '$array[id]'");
            $num = self::total(array('table' => 'meal_take_record', 'where' => "orderId = '$array[id]'"));
            $staffName = '';
            $all = find(array('table' => 'meal_take_record', 'where' => "orderId = '$array[id]'"));
            foreach ($all['array'] as $val) {
                $staffName .= self::findStaff($val['staffId']);
            }
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'stName' => $staffName,
                "hallName" => $hall['name'],
                "workFlow" => $array['workFlow'],
                "recordDate" => $array['recordDate'],//状态
                "mealType" => $array['mealType'],
                "num" => $num,
                "type" => '代取餐',
                'time' => $array['time'],
                'takeStName' => self::findStaff($take['staffId']) ?: ' ',
                'takeTime' => $take['time'] ?: ' ',
            );
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 取餐
     */
    public function takeMealEdit()
    {
        $hallId = $this->post('hallId');
        $date = $this->post('recordDate');
        $staffArr = $_POST['staffOption'] ? json_decode($_POST['staffOption'], true) : [];
        $mealType = $this->post('mealType');
        $hall = query('dining_hall', "id = '$hallId'");
        $warn = '';
        if (is_array($staffArr)) {
            foreach ($staffArr as $staff) {
                $meal_report = query('meal_report', "recordDate = '$date' and hallId = '$hallId' and mealType = '$mealType' and staffId = '$staff[stid]' and type in ('报餐','代报餐')");
                if (empty($meal_report['id'])) {
                    $warn = "未找到员工【{$staff['name']}】的报餐记录";
                    break;
                } elseif ($meal_report['workFlow'] == '已取餐') {
                    $warn = "员工【{$staff['name']}】已取餐";
                    break;
                }
            }
        }
        $dining_hall_detail = query('dining_hall_detail', "orderId = '$hallId' and mealType = '$mealType'");
        if (empty($hall['id'])) {
            $this->resp['warn'] = '未找到此食堂';
        } elseif (empty($date)) {
            $this->resp['warn'] = '未找到日期';
        } elseif (empty($mealType) || !in_array($mealType, explode('，', para('mealOption')))) {
            $this->resp['warn'] = '未找到餐别';
        } elseif (empty($staffArr)) {
            $this->resp['warn'] = '请选择需要取餐的员工';
        } elseif (strtotime($this->date . ' ' . $dining_hall_detail['mealStartTime']) > time()) {
            $this->resp['warn'] = '还未到' . $mealType . '的就餐时间，' . $mealType . '的就餐时间为:' . $dining_hall_detail['mealStartTime'] . '至' . $dining_hall_detail['mealEndTime'];
        } elseif (strtotime($this->date . ' ' . $dining_hall_detail['mealEndTime']) < time()) {
            $this->resp['warn'] = $mealType . '的就餐时间已结束，' . $mealType . '的就餐时间为:' . $dining_hall_detail['mealStartTime'] . '至' . $dining_hall_detail['mealEndTime'];
        } elseif ($warn) {
            $this->resp['warn'] = $warn;
        } else {
            //判断当前时间是否可报餐
            $this->startTrans();
            $id = self::getId();
            $warn = static::insert(array(
                'table' => 'meal_take_record_parent',
                'field' => [
                    'id' => $id,
                    'recordDate' => $date,
                    'hallId' => $hall['id'],
                    'mealType' => $mealType,
                    'type' => '代取餐',
                    'stid' => self::$stid,
                ]
            ));
            foreach ($staffArr as $staff) {
                $meal_report = query('meal_report', "recordDate = '$date' and hallId = '$hallId' and mealType = '$mealType' and staffId = '$staff[stid]' and type in ('报餐','代报餐')");
                $bool = static::insert(array(
                    'table' => 'meal_take_record',
                    'field' => [
                        'id' => self::getId(),
                        'orderId' => $id,
                        'reportId' => $meal_report['id'],
                        'recordDate' => $date,
                        'hallId' => $hall['id'],
                        'mealType' => $mealType,
                        'type' => '代取餐',
                        'departmentId' => self::findStaffDepartment($staff['stid'], 'id'),
                        'staffId' => $staff['stid'],
                        'num' => 1,
                        'takeStid' => self::$stid,
                    ]
                ));
                if ($bool != '新增成功') {
                    $warn = '新增取餐记录失败';
                    break;
                }
                $bool = static::update(array(
                    'table' => 'meal_report',
                    'field' => [
                        'workFlow' => '已取餐',
                    ],
                    'where' => "id = '$meal_report[id]'"
                ));
                if ($bool != '更新成功') {
                    $warn = '修改取餐状态失败';
                    break;
                }
            }
            if ($warn == '新增成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '取餐成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = $warn;
            }
        }
    }


    /**
     * 取客餐
     */
    public function takeClientMeal(){
        $id = $this->post('id');
        $meal_report = query('meal_report',"id = '$id'");
        $dining_hall_detail = query('dining_hall_detail', "orderId = '$meal_report[hallId]' and mealType = '$meal_report[mealType]'");
        if (empty($id) || empty($meal_report['id'])){
            $this->resp['warn'] = '未找到ID';
        }elseif($meal_report['workFlow'] !='待取餐'){
            $this->resp['warn'] = '此报餐已经取走了';
        }elseif($meal_report['recordDate'] !=$this->date){
            $this->resp['warn'] = '这不是今天的餐';
        }elseif (strtotime($meal_report['recordDate'] . ' ' . $dining_hall_detail['mealStartTime']) > time()) {
            $this->resp['warn'] = '还未到' . $meal_report['mealType'] . '的就餐时间，' .  $meal_report['mealType']  . '的就餐时间为:' . $dining_hall_detail['mealStartTime'] . '至' . $dining_hall_detail['mealEndTime'];
        } elseif (strtotime($meal_report['recordDate'] . ' ' . $dining_hall_detail['mealEndTime']) < time()) {
            $this->resp['warn'] =  $meal_report['mealType']  . '的就餐时间已结束，' .  $meal_report['mealType']  . '的就餐时间为:' . $dining_hall_detail['mealStartTime'] . '至' . $dining_hall_detail['mealEndTime'];
        } else{
            //判断当前时间是否可报餐
            $this->startTrans();
            $id = self::getId();
            $warn = static::insert(array(
                'table' => 'meal_take_record_parent',
                'field' => [
                    'id' => $id,
                    'recordDate' => $meal_report['recordDate'],
                    'hallId' => $meal_report['hallId'],
                    'mealType' => $meal_report['mealType'],
                    'stid' => self::$stid,
                ]
            ));
            $bool = static::insert(array(
                'table' => 'meal_take_record',
                'field' => [
                    'id' => self::getId(),
                    'orderId' => $id,
                    'reportId' => $meal_report['id'],
                    'recordDate' => $meal_report['recordDate'],
                    'hallId' => $meal_report['hallId'],
                    'mealType' =>$meal_report['mealType'],
                    'type' => '客餐取餐',
                    'departmentId' => '',
                    'staffId' =>'',
                    'num' => $meal_report['num'],
                    'takeStid' => self::$stid,
                ]
            ));
            if ($bool != '新增成功') {
                $warn = '新增取餐记录失败';
            }
            $bool = static::update(array(
                'table' => 'meal_report',
                'field' => [
                    'workFlow' => '已取餐',
                ],
                'where' => "id = '$meal_report[id]'"
            ));
            if ($bool != '更新成功') {
                $warn = '修改取餐状态失败';
            }
            if ($warn == '新增成功') {
                $this->commitTrans();
                $this->code = 1;
                $this->resp['warn'] = '取餐成功';
            } else {
                $this->rollback();
                $this->resp['warn'] = $warn;
            }
        }
    }


    /**
     * 获取满意度选项
     */
    public function getSatisfaction()
    {
        $this->code = 1;
        $this->resp['data'] = explode('，', para('hallEvaluateOption'));
    }

    /**
     * 提交食堂评价
     */
    public function satisfactionEdit()
    {
        $field = array(
            'id' => self::getId(),
            'orderId' => $this->post('hallId'),
            'recordDate' => $this->post('recordDate'),
            'mealType' => $this->post('mealType'),
            'satisfaction' => $this->post('workFlow'),
            'text' => $this->post('text'),
            'stid' => self::$stid
        );
        $annotation = [
            'orderId' => '食堂',
            'recordDate' => '日期',
            'mealType' => '餐别',
            'satisfaction' => '评价',
        ];
        $rules = [
            'orderId' => 'required',
            'recordDate' => 'required',
            'mealType' => 'required',
            'satisfaction' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
        } elseif (self::total(array('table' => 'dining_hall_ass', 'where' => "orderId = '$field[orderId]' and recordDate = '$field[recordDate]' and mealType = '$field[mealType]' and stid = '" . self::$stid . "'")) > 0) {
            $this->resp['warn'] = '您已经评价了这一餐';
        } else {
            //判断当前时间是否可报餐
            $warn = static::insert(array(
                'table' => 'dining_hall_ass',
                'field' => $field
            ));
            if ($warn == '新增成功') {
                $this->code = 1;
                $this->resp['warn'] = '评价成功';
            } else {
                $this->resp['warn'] = '评价失败';
            }
        }
    }

    /**
     * 食堂统计
     */
    public function statistics()
    {
        //数据查询
        $month = $this->post('month');//切换月份
        $hallId = $this->post('hallId');//食堂ID
        if ($month) {
            $date = $month . '-01';
        } else {
            $date = $this->post('date') ?: $this->date;
        }
        $this->code = 1;
        $month = date('Y-m', strtotime($date));//月份
        $days = date('t', strtotime($date));  //此月份总天数
        $dayArr = [];
        $now_week = date('w', strtotime(date('Y-m-01', strtotime($date))));
        //默认食堂
        if (!$hallId){
            $hall = query('dining_hall',"order by time asc");
            $hallId = $hall['id'];
        }else{
            $hall = query('dining_hall',"id = '$hallId'");
        }
        $hallName = $hall['name'];

        //报餐取餐统计
        $list = [];
        $mealTypeOption = explode('，', para('mealOption'));
        foreach ($mealTypeOption as $val){
            $askNum = find(array('table'=>'meal_report','where'=>"recordDate = '$date' and hallId ='$hallId' and mealType = '$val' ",'sum'=>'num'));
            $takeNum = find(array('table'=>'meal_report','where'=>"recordDate = '$date' and hallId ='$hallId'  and mealType = '$val' and workFlow = '已取餐'",'sum'=>'num'));
            $askClientNum = find(array('table'=>'meal_report','where'=>"recordDate = '$date' and hallId ='$hallId'  and mealType = '$val' and type ='申请客餐'",'sum'=>'num'));
            $takeClientNum = find(array('table'=>'meal_report','where'=>"recordDate = '$date' and hallId ='$hallId'  and mealType = '$val' and type ='申请客餐' and workFlow = '已取餐'",'sum'=>'num'));
            $list[] = [
                'mealType'=>$val,
                'reportNum'=>$askNum,
                'takeNum'=>$takeNum,
                'client_report_num'=>$askClientNum,
                'client_take_num'=>$takeClientNum,
                'text'=>$askNum.' / '.$takeNum."（客餐 {$askClientNum} / {$takeClientNum}）"
            ];
        }
        for ($i = 0; $i < $now_week; $i++) {
            $dayArr[] = [
                'index' => ' ',
                'state' => ' ',
                'date' => ' ',
            ];
        }
        for ($i = 1; $i <= $days; $i++) {
            $today = $month . '-' . sprintf("%02d", $i);
            $dayArr[] = [
                'index' => $i,
                'date' => $today,
                'state' => '',
            ];
        }
        $w = date('w',strtotime($date));//当前日期为周几
        $d = $w?$w-1:6;//周日需减6天
        $startDate = date('Y-m-d',strtotime("-{$d} day",strtotime($date)));
        $xData = [];
        $yData = [];
        for ($i=0;$i<=6;$i++){
            $xData[] = date('m-d',strtotime("+{$i} day",strtotime($startDate)));
        }
        foreach ($mealTypeOption as $val){
            $temp = [];
            $temp['type'] ='bar';
            $temp['name'] =$val;
            for ($i=0;$i<=6;$i++){
                $today = date('Y-m-d',strtotime("+{$i} day",strtotime($startDate)));
                $askNum = find(array('table'=>'meal_report','where'=>"recordDate = '$today' and hallId ='$hallId'  and mealType = '$val' and type in ('报餐','代报餐')",'sum'=>'num'));
                $askClientNum = find(array('table'=>'meal_report','where'=>"recordDate = '$today' and hallId ='$hallId'  and mealType = '$val' and type ='申请客餐'",'sum'=>'num'));
                $temp['data'][] = $askNum+$askClientNum;
            }
            $yData[] = $temp;
        }


        $data['result'] = [
            'date' => $date,
            'month' => $month,
            'formatDate' => date('m月d日', strtotime($date)) . ' 周' . $this->weekArray[date("w", strtotime($date))] . ' ' . ($date == $this->date ? '(今天)' : ''),
            'list' => $dayArr,
            'statistics' => $list,
            'xData'=>$xData,
            'yData'=>$yData,
            'hallName'=>$hallName,
            'hallId'=>$hallId,
        ];
        $this->resp['data'] = $data;

    }

    /**
     * 统计详情
     */
    public function statisticsDetail(){
        $recordDate = $this->post('recordDate');
        $hallId = $this->post('hallId');
        $mealType = $this->post('mealType');
        $classify = $this->post('classify');
        $list = [];
        $people = [];
        $peopleNum=0;
        if (empty($classify)){
            $this->resp['warn'] = '未找到类别';
        }elseif(empty($recordDate)){
            $this->resp['warn'] = '未找到日期';
        }elseif(empty($hallId)){
            $this->resp['warn'] = '未找到食堂';
        }elseif(empty($mealType)){
            $this->resp['warn'] = '未找到餐别';
        }else{
            if ($classify =='报餐'){
                $all = find(array('table'=>'meal_report as a join meal_report_detail as b on a.id = b.orderId','where'=>"a.recordDate = '$recordDate' and a.hallId = '$hallId' and a.mealType = '$mealType' group by b.menuId ",'field'=>"ifnull(sum(any_value(b.num)),0) as total,menuId"));
                foreach ($all['array'] as $array){
                    $menu = query('dining_menu',"id = '$array[menuId]'");
                    $img = query('file', "targetId = '$array[menuId]' order by time asc");
                    $list[] = array(
                        'menuId'=>$array['menuId'],
                        'name'=>$menu['name'],
                        'type'=>$menu['type'],
                        'ico'=>self::fillSrc($img['src']),
                        'num'=>$array['total']
                    );
                }
                //人数
                $peopleNum=0;

                $all = find(array('table'=>'meal_report','where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type in ('报餐','代报餐')"));
                foreach ($all['array'] as $array){
                    $staff = query('staff',"stid = '$array[staffId]'");
                    $job = query('job',"id = '$staff[jobId]'");
                    $people[] = [
                        'name'=>$staff['name'],
                        'ico'=>self::fillSrc($staff['ico']),
                        'title'=>self::findStaffDepartment($staff['stid']).'-'.$job['name']
                    ];
                    $peopleNum+=$array['num'];
                }
                $clientMealNum =find(array('table'=>'meal_report','sum'=>"num",'where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type ='申请客餐'"));
                $people[]=[
                    'name'=>'客餐',
                    'ico'=>self::fillSrc('img/miniProgram/oa/clientMeal.png'),
                    'title'=>$clientMealNum.'份'
                ];
            }elseif($classify =='取餐'){
                $all = find(array('table'=>'meal_take_record as a join meal_report as c on a.reportId = c.id join meal_report_detail as b on b.orderId = c.id','where'=>"a.recordDate = '$recordDate' and a.hallId = '$hallId' and a.mealType = '$mealType'  group by b.menuId ",'field'=>"ifnull(sum(any_value(b.num)),0) as total,menuId"));
                foreach ($all['array'] as $array){
                    $menu = query('dining_menu',"id = '$array[menuId]'");
                    $img = query('file', "targetId = '$array[menuId]' order by time asc");
                    $list[] = array(
                        'menuId'=>$array['menuId'],
                        'name'=>$menu['name'],
                        'type'=>$menu['type'],
                        'ico'=>self::fillSrc($img['src']),
                        'num'=>$array['total']
                    );
                }
                //人数
                $peopleNum=0;
                $all = find(array('table'=>'meal_take_record','where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type in ('取餐','代取餐')"));
                foreach ($all['array'] as $array){
                    $staff = query('staff',"stid = '$array[staffId]'");
                    $job = query('job',"id = '$staff[jobId]'");
                    $people[] = [
                        'name'=>$staff['name'],
                        'ico'=>self::fillSrc($staff['ico']),
                        'title'=>self::findStaffDepartment($staff['stid']).'-'.$job['name']
                    ];
                    $peopleNum+=$array['num'];
                }
                $clientMealNum =find(array('table'=>'meal_take_record','sum'=>"num",'where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type ='客餐取餐'"));
                $people[]=[
                    'name'=>'客餐',
                    'ico'=>self::fillSrc('img/miniProgram/oa/clientMeal.png'),
                    'title'=>$clientMealNum.'份'
                ];
            }elseif($classify =='未取餐'){
                $all = find(array('table'=>'meal_report as a join meal_report_detail as b on a.id = b.orderId','where'=>"a.recordDate = '$recordDate' and a.hallId = '$hallId' and a.mealType = '$mealType' and a.workFlow='待取餐' group by b.menuId ",'field'=>"ifnull(sum(any_value(b.num)),0) as total,menuId"));
                foreach ($all['array'] as $array){
                    $menu = query('dining_menu',"id = '$array[menuId]'");
                    $img = query('file', "targetId = '$array[menuId]' order by time asc");
                    $list[] = array(
                        'menuId'=>$array['menuId'],
                        'name'=>$menu['name'],
                        'type'=>$menu['type'],
                        'ico'=>self::fillSrc($img['src']),
                        'num'=>$array['total']
                    );
                }
                //人数
                $peopleNum=0;
                $all = find(array('table'=>'meal_report','where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type in ('报餐','代报餐') and workFlow='待取餐'"));
                foreach ($all['array'] as $array){
                    $staff = query('staff',"stid = '$array[staffId]'");
                    $job = query('job',"id = '$staff[jobId]'");
                    $people[] = [
                        'name'=>$staff['name'],
                        'ico'=>self::fillSrc($staff['ico']),
                        'title'=>self::findStaffDepartment($staff['stid']).'-'.$job['name']
                    ];
                    $peopleNum+=$array['num'];
                }
                $clientMealNum =find(array('table'=>'meal_report','sum'=>"num",'where'=>"recordDate = '$recordDate' and hallId = '$hallId' and mealType = '$mealType' and type ='申请客餐'and workFlow='待取餐'"));
                $people[]=[
                    'name'=>'客餐',
                    'ico'=>self::fillSrc('img/miniProgram/oa/clientMeal.png'),
                    'title'=>$clientMealNum.'份'
                ];
            }

            $this->code = 1;
            $this->resp['data'] = [
                'list'=>$list,
                'people'=>$people,
                'peopleNum'=>$peopleNum
            ];
        }






    }
}
